#coding:utf-8
import sys
from Tkinter import *

import time
import random
import itertools
import os
import wget
import string
import code
import sys
reload(sys)   
sys.setdefaultencoding('utf8') 
from fake_useragent import UserAgent
ua = UserAgent()
import requests
from lxml import etree
headers = {
			"User-Agent":ua.random,
			"Accept":"*/*",
			"Accept-Encoding":"gzip, deflate",
			"Accept-Language":"zh-CN,zh;q=0.8",
			
			'Upgrade-Insecure-Requests':'1',
			"Connection":"keep-alive",
			}

class MaiZi():
	def __init__(self):
		self.root = Tk()
		self.root.geometry('680x660+100+20')
		self.fm1 = Frame(self.root,bg = '',width = 680,height = 4)			
		self.fm2 = Frame(self.root,bg = '',width = 680,height = 4)

		self.root.title('麦子学院课程下载神器 V1.0版（有bug）--BY Jake  联系邮箱：jakejie@163.com')

		self.text_design()
		self.BT_design()
		self.info_design()

		self.fm1.pack()
		self.fm2.pack()
		self.root.mainloop()
	

	#文本框的设置
	def text_design(self):
		#课程链接文本输入框
		self.course_url = Entry(self.fm1,borderwidth = 3,width = 34,font=("Purisa",18))
		self.course_url.grid(row = 1,column = 1)		
		#自动填充文本框，课程相关信息
		self.course_name = Entry(self.fm1,borderwidth = 3,width = 34,font=("Purisa",18))
		self.course_name.grid(row = 3,column = 1)
		self.course_jianjie = Entry(self.fm1,borderwidth = 3,width = 34,font=("Purisa",18))
		self.course_jianjie.grid(row = 4,column = 1)
		self.course_tag = Entry(self.fm1,borderwidth = 3,width = 34,font=("Purisa",18))
		self.course_tag.grid(row = 6,column = 1)
		self.course_teacher = Entry(self.fm1,borderwidth = 3,width = 34,font=("Purisa",18))
		self.course_teacher.grid(row = 5,column = 1)
		self.course_teacher_jianjie = Entry(self.fm1,borderwidth = 3,width = 34,font=("Purisa",18))
		self.course_teacher_jianjie.grid(row = 7,column = 1)
		self.course_play_times = Entry(self.fm1,borderwidth = 3,width = 34,font=("Purisa",18))
		self.course_play_times.grid(row = 8,column = 1)
		self.course_QQ = Entry(self.fm1,borderwidth = 3,width = 34,font=("Purisa",18))
		self.course_QQ.grid(row = 9,column = 1)
		self.save_path = Entry(self.fm1,borderwidth = 3,width = 34,font=("Purisa",18))
		self.save_path.grid(row = 10,column = 1)

		#定义下载进度提示文本显示框
		self.down_info = Text(self.fm2,borderwidth = 6,width = 50,height = 8,font=("Purisa",16))
		self.down_info.grid(row = 1,column = 0)

	#按钮设置
	def BT_design(self):
		#定义获取课程信息按钮
		search_button = Button(self.fm1,text = "获取课程信息",bg = 'green',width = 30,height = 2, command = self.input_url)
		search_button.grid(row = 2,column = 1)
		#定义退出下载按钮
		self.quit_button = Button(self.fm1,text = "退出",width = 27,height = 2,fg = 'red',command = self.root.quit)
		self.quit_button.grid(row = 2,column = 0)
		#定义下载课程按钮
		self.down = Button(self.fm1,text = "下载该课程",width = 30,height = 2,fg = 'red',command = self.downs)
		self.down.grid(row = 11,column = 1)
		#定义清空所有输入信息按钮
		self.quit_button = Button(self.fm1,text = "清空所有信息",width = 30,height = 2,fg = 'red',command = self.Empty)
		self.quit_button.grid(row = 11,column = 0)		

	#提示信息框
	def info_design(self):
		#需要下载发课程链接输入框
		label = Label(self.fm1,text = ' 课 程 链 接 :',font=("Purisa",12), fg = 'red',width = 24,height = 2)
		label.grid(row = 1)

		#定义显示获取到的课程相关信息显示框
		self.label1 = Label(self.fm1,text = ' 课程 名称 :',font=("Purisa",12),width = 24,height = 2)
		self.label1.grid(row = 3,column = 0)
		self.label2 = Label(self.fm1,text = ' 课程 简介 :',font=("Purisa",12),width = 24,height = 2)
		self.label2.grid(row = 4,column = 0)
		self.label3 = Label(self.fm1,text = ' 课程 老师 :',font=("Purisa",12),width = 24,height = 2)
		self.label3.grid(row = 5,column = 0)
		self.label4 = Label(self.fm1,text = '课程标签分类:',font=("Purisa",12),width = 24,height = 2)
		self.label4.grid(row = 6,column = 0)
		self.label5 = Label(self.fm1,text = '课程老师简介:',font=("Purisa",12),width = 24,height = 2)
		self.label5.grid(row = 7,column = 0)
		self.label6 = Label(self.fm1,text = '课程播放次数:',font=("Purisa",12),width = 24,height = 2)
		self.label6.grid(row = 8,column = 0)
		self.label7 = Label(self.fm1,text = '课程交流QQ群:',font=("Purisa",12),width = 24,height = 2)
		self.label7.grid(row = 9,column = 0)
		self.label8 = Label(self.fm1,text = '课程保存位置:',font=("Purisa",12),width = 24,height = 2)
		self.label8.grid(row = 10,column = 0)

	#调用课程详情数据
	def input_url(self):
		self.url = self.course_url.get()
		if 'http' in self.url :
			if 'www.maiziedu.com' in self.url :
				if 'course' in self.url :
					self.down_info.delete('1.0',END)
					self.down_info.insert(INSERT,"正在获取课程信息....")
					return self.get_couse(self.url)
		else :
			self.down_info.delete('1.0',END)
			self.down_info.insert(INSERT,"请输入正确的网页链接！如：http://www.maiziedu.com/course/数字/")
	#获取课程详情数据
	def get_couse(self,url) :
		self.Empty()

		#print self.url
		html = self.Requests_html(self.url)
		tree = etree.HTML(html.text)
		#课程名
		course_name = tree.xpath('/html/body/div[4]/div[2]/h1/text()')
		if len(course_name) == 0 :
			self.down_info.delete('1.0',END)
			self.down_info.insert(INSERT, "请输入正确的网页链接！如：http://www.maiziedu.com/course/18/")
		else:
			self.name = course_name[0]
		#课程简介
		course_jianjie = tree.xpath('/html/body/div[4]/div[2]/p[1]/text()')
		if len(course_jianjie) == 0 :
			course_jianjie = ["其他"]		
		#课程标签分类
		course_tag = tree.xpath('/html/body/div[4]/div[2]/p[2]/a/text()')
		#/html/body/div[4]/div[2]/p[2]/a
		if len(course_tag) == 0 :
			course_tag = ["其他"]
		#讲课老师
		course_teacher = tree.xpath('/html/body/div[5]/div[2]/div[1]/div/h3/text()')
		if len(course_teacher) == 0 :
			course_teacher = ["其他"]		
		#讲课老师简介
		course_teacher_jianjie = tree.xpath('/html/body/div[5]/div[2]/div[1]/p/text()')
		if len(course_teacher_jianjie) == 0 :
			course_teacher_jianjie = ["无"]
		#课程播放次数
		course_play_times = tree.xpath('/html/body/div[4]/div[2]/p[3]/span[2]/text()')
		if len(course_play_times) == 0 :
			course_play_times = ["无"]		
		#课程交流QQ群
		course_QQ = tree.xpath('/html/body/div[4]/div[2]/p[4]/a[2]/text()')
		course_QQ = ["-*-".join(itertools.chain(course_QQ)).replace(';','')]

		#插入获取到的课程信息到文本框
		self.course_name.insert(0,course_name[0])
		self.course_jianjie.insert(0,course_jianjie[0])
		self.course_tag.insert(0,course_tag[0])		
		self.course_teacher.insert(0,course_teacher[0])
		self.course_teacher_jianjie.insert(0,course_teacher_jianjie[0])
		self.course_play_times.insert(0,course_play_times[0])
		self.course_QQ.insert(0,course_QQ[0])
		self.save_path.insert(0,"F:\\MaiZi")
		#课程章节信息：
		#		章节目录----URL链接
		self.chapter = []
		name_url = tree.xpath('/html/body/div[5]/div[1]/div/div[1]/ul/li')
		for li in name_url:
			chapter_name = li.xpath('a/span[1]/text()')
			chapter_url = li.xpath('a/@href')
			chapter_name = chapter_name[0]
			chapter_url = 'http://www.maiziedu.com' + chapter_url[0]
			chapters = [chapter_name,chapter_url]
			self.chapter.append(chapters)
		return self.chapter
	#调用课程下载函数
	def downs(self):
		path =  self.save_path.get()
		#下载课程存储文件夹地址
		if self.name == None :
			self.down_info.delete('1.0',END)

			self.down_info.insert(INSERT, "请输入正确的网页链接！如：http://www.maiziedu.com/course/数字/")
		else:
			path1 = path + '\\'+self.name.decode('utf-8')
			self.infos =self.chapter
			#self.msg1['text'] = "******正在下载中******"
			for self.info in self.infos:
				#print self.info[0]
				self.down_info.delete('1.0',END)
				self.down_info.insert(INSERT,"视频播放页面链接")
				"""
				self.down_info.delete('1.0',END)
				self.down_info.insert(INSERT,"视频播放页面链接：%s\
					课程名：%s\
					章节名：%s\
					下载链接：%s\
					"%(urls,path1,path2,urls))
				"""
				self.download(path1,self.info[0],self.info[1])
	#根据传入的URL链接，下载当前视频课程
	def download(self,path1,path2,urls):


		#self.msg2['text'] = ""
		#self.msg3['text'] = ""
		#self.msg4['text'] = "From ："
		try:
			html = self.Requests_html(urls)
			com = re.compile(r'lessonUrl = "http://newoss\.maiziedu\.com/.*?\.mp4')
			url = re.findall(com,html.text)
			#创建文件夹，用path参数命名
			#path1 = path1.replace('\\','')
			#savepath = "F:\\MaiZi\\" + path1
			savepath = path1
			if(os.path.exists(savepath) == False):
				os.makedirs(savepath)
			savepath = savepath + "\\"
			down_urls = url[0][13:]
			#print "下载链接：%s"%down_urls
			wget.download(down_urls,(str(savepath) + path2 + '.mp4').decode('utf-8'))
			self.down_info.insert(INSERT, "我的视频下载完了哦！")
			time.sleep(5)
			return True
		except :
			self.down_info.delete('1.0',END)
			self.down_info.insert(INSERT, "****************下载错误*************")
			return False
	#清空消息框内所有内容
	def Empty(self):
		#清空文本框内数据

		self.course_name.delete(0,END) 
		self.course_jianjie.delete(0,END) 
		self.course_tag.delete(0,END) 
		self.course_teacher.delete(0,END) 
		self.course_teacher_jianjie.delete(0,END) 
		self.course_play_times.delete(0,END) 
		self.course_QQ.delete(0,END) 
		self.save_path.delete(0,END)



	def Requests_html(self,url):
		#自定义请求头部，该网站不需要登录或者cookie信息也可以获取到数据
		self.headers = {
					'User-Agent':ua.random,
					"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
					"Accept-Encoding":"gzip, deflate, sdch",
					"Accept-Language":"zh-CN,zh;q=0.8",
					"Cache-Control":"max-age=0",
					"Connection":"keep-alive",
					}
		try:
			req = requests.get(url,headers = self.headers)
			return req
		except :
			return False


#http://www.maiziedu.com/course/18/
#http://www.maiziedu.com/course/751/
maizi = MaiZi()
